package com.erb.controller.wzq;

import com.erb.common.Constant;
import com.erb.common.VerifyCodeUtils;
import com.erb.entity.User;
import com.erb.service.wzq.IUserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.Random;

/**
 * Created by MoYao on 2020/6/9.
 */
@Controller
@RequestMapping("/user")
public class UserController {

	int codes = 0;

	@Resource
	private IUserService ius;

	/**
	 * 获取验证码图片
	 **/
	@RequestMapping(value = "/image", method = RequestMethod.GET)
	public void image(HttpServletResponse response, HttpSession session) throws IOException {
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/jpeg");
		// 生成随机字串
		String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
		session.removeAttribute("verCode");
		session.removeAttribute("codeTime");

		session.setAttribute("verCode", verifyCode.toLowerCase());
		session.setAttribute("codeTime", LocalDateTime.now());

		// 生成图片
		int w = 100, h = 30;
		OutputStream out = response.getOutputStream();
		VerifyCodeUtils.outputImage(w, h, out, verifyCode);
	}

	/**
	 * 核对图形验证码
	 **/
	@RequestMapping("/valid")
	@ResponseBody
	public int valid(String code, @SessionAttribute("verCode") Object verCode, HttpSession session) {

		if (null == verCode) {
			session.setAttribute("error", "验证码已失效，请重新输入");
			return 1;
		}
		String verCodeStr = verCode.toString();
		LocalDateTime localDateTime = (LocalDateTime) session.getAttribute("codeTime");

		long past = localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
		long now = LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();

		if (verCodeStr == null || code == null || code.isEmpty() || !verCodeStr.equalsIgnoreCase(code)) {

			session.setAttribute("error", "验证码错误");
			return 2;

		} else if ((now - past) / 1000 / 60 > 2) {//两分钟
			session.setAttribute("error", "验证码已过期，重新获取");
			return 3;
		} else {
			//验证成功，删除存储的验证码
			session.removeAttribute("verCode");
			return 0;
		}
	}

	//登录验证
	@RequestMapping("/login_verification")
	@ResponseBody
	public Boolean login_verification(String phoneemail, String password, HttpSession session) {
		User user = ius.emailuserphone(phoneemail, password);
		if (user == null) {
			return false;
		} else {
			user.setPassword("");
			session.setAttribute("user", user);
			SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			ius.userupd(sf.format(new Date()), user.getId());
			return true;
		}
	}

	//验证用户名是否存在
	@RequestMapping("/seluser")
	@ResponseBody
	public int seluser(User user) {
		User user1 = ius.usersel(user);
		if (user1 != null) {  //用户名或号码存在时
			return 1;
		} else {
			return 0;
		}
	}

	//生成短信验证码
	@RequestMapping("/dxyzm")
	@ResponseBody
	public int dxyzm(String phone) {
		Random random = new Random();
//        int i = random.nextInt(999999);  //随机生成6位数字
		int i = 111111;
		codes = i;
//        VerificationCode vc = new VerificationCode();
//        vc.vercode(phone, i);
		return 0;
	}

	//验证短信验证码
	@RequestMapping("/yzdxyzm")
	@ResponseBody
	public int yzdxyzm(int code) {
		if (code != codes) {
			return 1;
		}
		return 0;
	}

	//添加用户
	@RequestMapping("/add")
	public String add(User user, String tname, Model model) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		user.setRegisterdate(sdf.format(new Date()));
		user.setIntegral(Constant.INITIAL_USER_POINTS);  //积分
		user.setModificationTime(Constant.MODIFIABLE_THIS_MONTH);  //本月可修改
		System.out.println("新增用户：" + user.toString());
		ius.useradd(user);  //添加新用户
		model.addAttribute("name", user.getName());  //新用户名字发布下
		if (tname != null && tname != "") {
			User user1 = ius.usersel(user);  //获取推荐人的id
			ius.recommendadd(user.getId(), user1.getId());
		}
		return "common/register1";
	}

	//退出登录
	@GetMapping("/cancellationuser")
	public String cancellationuser(HttpSession session) {
		session.invalidate();  //清除所有session
		return "common/index";
	}
}
